/*
* Copyright 2018 Shanxi Lu'an Taihang Laihui Net Tech co.,LTD.
*/
package com.laihuichuxing.train.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.laihuichuxing.common.util.DateUtil;
import com.laihuichuxing.common.util.JsonUtil;
import com.laihuichuxing.config.CodeUtil;
import com.laihuichuxing.config.ParameterConfig;
import com.laihuichuxing.order.train.api.OpTicketServerApi;
import com.laihuichuxing.order.train.api.TrainOrderServerApi;
import com.laihuichuxing.order.train.entity.OrderRecord;
import com.laihuichuxing.order.train.entity.Passenger;
import com.laihuichuxing.order.train.entity.TrainOrder;
import com.laihuichuxing.train.dao.*;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author: Qinxuefeng
 * @since: 1.0
 * Create Date Time: 2018/12/14 11:58
 * Update Date Time:
 */
@Service(version = "1.0.0",interfaceClass = TrainOrderServerApi.class)
public class TrainOrderServerProvider implements TrainOrderServerApi {
    @Autowired
    private OPticketDAO oPticketDAO;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private TrainBuyOrderDao trainBuyOrderDao;
    @Autowired
    private TrainOrderDao trainOrderDao;
    @Autowired
    private TrainPayDao trainPayDao;
    @Autowired
    private OpTicketServerApi opTicketServerApi;
    @Override
    public Map<String, Object> bookSeat(String param, Map<String, String> paramMap) {
        JSONObject paramJson = JSONObject.parseObject(param);
        String orderNo = paramJson.getString(ParameterConfig.ORDERNO);
        int exist = oPticketDAO.selectExist(orderNo);
        if (exist > 0) {
            return JsonUtil.getChuanglvJson(100, "成功");
        }
        String passengerJson = paramJson.getString("passengers");
        List<Map<String, Object>> passengerList = JsonUtil.parseList(passengerJson);
        //占座失败
        if (!CodeUtil.CODE.equals(paramJson.getString(ParameterConfig.MSGCODE))) {
            Map<String, String> cancelMap = new HashMap<>();
            cancelMap.put(ParameterConfig.ORDERNO, orderNo);
            //占座失败，取消订单
            Map<String, Object> res = opTicketServerApi.cancelOrder(paramMap, 3, 0);
            //改签单占座失败，更改订单状态
            if (paramJson.getInteger("isChangedOrder") == 1) {
                changeOrderStatus(paramJson, orderNo, passengerList);
            } else {
                trainOrderDao.updateOrderstatus(orderNo,"3");
                //更新订单表相关表
                Map<String, Object> m = new HashMap<>();
                Map<String, Object> condition = new HashMap<>();
                Map<String, Object> columns = new HashMap<>();
                m.put(ParameterConfig.TABLE, ParameterConfig.JHCX_TRAIN_ORDER_RECORD);
                condition.put(ParameterConfig.ORDERNO, orderNo);
                columns.put(ParameterConfig.IS_ENABLE, 0);
                m.put(ParameterConfig.COLUMNS, columns);
                m.put(ParameterConfig.CONDITIONS, condition);
                oPticketDAO.updateEnable(m);
                //更新乘客表
                passengerList.forEach(passenger -> {
                    String idCard = MapUtils.getString(passenger, ParameterConfig.CARDNO);
                    passenger.remove(ParameterConfig.CARDNO);
                    Map<String, Object> map = new HashMap<>();
                    Map<String, Object> conditions = new HashMap<>();
                    map.put(ParameterConfig.TABLE, ParameterConfig.JHCX_TRAIN_PASSENGER);
                    passenger.put(ParameterConfig.STATE, 3);
                    conditions.put(ParameterConfig.ORDERNO, orderNo);
                    conditions.put("idCard", idCard);
                    passenger.remove("cardType");
                    map.put(ParameterConfig.COLUMNS, passenger);
                    map.put(ParameterConfig.CONDITIONS, conditions);
                    oPticketDAO.update(map);
                });
            }
            return JsonUtil.getChuanglvJson(999, "占座失败");
        } else {
            //--------占座成功
            Map<String, Object> dataMap = new HashMap<>();
            Map<String, Object> pMap = new HashMap<>();
            pMap.put(ParameterConfig.NOTIFY, param);
            pMap.put(ParameterConfig.ORDERNO, orderNo);
            pMap.put(ParameterConfig.CREATE_TIME, DateUtil.getCurrentTime());
            pMap.put("type", 1);
            dataMap.put(ParameterConfig.PARAM, pMap);
            dataMap.put(ParameterConfig.TABLE_NAME, ParameterConfig.JHCX_TRAIN_NOTIFY);
            int count = commonDao.insertOne(dataMap);
            if (count == 0) {
                return JsonUtil.getChuanglvJson(999, "通知失败");
            }
            //改签单
            if (paramJson.getInteger("isChangedOrder") == 1) {
                String originalOrderNo = paramJson.getString(ParameterConfig.ORIGINALORDERNO);
                //改签类型
                String changedType = paramJson.getString("changedType");
                //差价
                double changePriceDiff = paramJson.getDouble("changePriceDiff");
                Passenger originalPassengerOrder = oPticketDAO.getPassengerOrder(paramJson.getString(ParameterConfig.ORIGINALORDERNO), passengerList.get(0).get(ParameterConfig.PASSENGERID_LOWER).toString());

                TrainOrder order = new TrainOrder();
                order.setOrderNo(orderNo);
                order.setState("13");
                order.setFromTime(paramJson.getString("departureTime"));
                order.setToTime("arrivalTime");
                order.setBookSeatTime(DateUtil.getCurrentTime());
                order.setChangedType(changedType);
                oPticketDAO.updateOrder(order);

                Passenger passer = new Passenger();
                passer.setOrderNo(orderNo);
                passer.setPassengerId(passengerList.get(0).get(ParameterConfig.PASSENGERID_LOWER).toString());
                passer.setState("15");
                passer.setPassengerName(passengerList.get(0).get("passengerName").toString());
                passer.setPassengerType(passengerList.get(0).get("passengerType").toString());
                passer.setIdCard(passengerList.get(0).get(ParameterConfig.CARDNO).toString());
                passer.setSeatClass(passengerList.get(0).get("seatClass").toString());
                passer.setSeatNo(passengerList.get(0).get("seatNo") != null ? passengerList.get(0).get("seatNo").toString() : null);
                passer.setPrice(passengerList.get(0).get("price").toString());
                passer.setTicketPrice(passengerList.get(0).get("price").toString());
                passer.setpTicketNo(passengerList.get(0).get("pTicketNo") != null ? passengerList.get(0).get("pTicketNo").toString() : null);
                passer.setServiceCharge(passengerList.get(0).get("serviceCharge").toString());
                passer.setInsuranceCharge(passengerList.get(0).get("insuranceCharge").toString());
                passer.setSex(originalPassengerOrder == null ? null : originalPassengerOrder.getSex());
                passer.setBirthday(originalPassengerOrder == null ? null : originalPassengerOrder.getBirthday());
                passer.setRefundPrice(changePriceDiff + "");
                passer.setOriginalOrderNo(originalOrderNo);
                oPticketDAO.insertPassengerOrder(passer);
                Passenger oldPasser = new Passenger();
                oldPasser.setOrderNo(originalOrderNo);
                oldPasser.setPassengerId(passengerList.get(0).get(ParameterConfig.PASSENGERID_LOWER).toString());
                oldPasser.setChangeOrderNo(orderNo);
                oldPasser.setState("14");
                oPticketDAO.specialMethodToChange(originalOrderNo, orderNo);
                return JsonUtil.getChuanglvJson(100, "占座成功");
            } else {
                //更新订单表
                Map<String, Object> orderMap = new HashMap<>();
                Map<String, Object> oMap = new HashMap<>();
                Map<String, Object> conditionMap = new HashMap<>();
                oMap.put(ParameterConfig.STATE, 2);
                oMap.put("bookSeatTime", DateUtil.getCurrentTime());
                conditionMap.put(ParameterConfig.ORDERNO, orderNo);
                orderMap.put(ParameterConfig.TABLE_NAME, ParameterConfig.JHCX_TRAIN_ORDER);
                orderMap.put(ParameterConfig.PARAM, oMap);
                orderMap.put("condition", conditionMap);
                commonDao.updateOne(orderMap);
                //更新乘客表
                passengerList.forEach(passenger -> {
                    String idCard = MapUtils.getString(passenger, ParameterConfig.CARDNO);
                    passenger.remove(ParameterConfig.CARDNO);
                    Map<String, Object> map = new HashMap<>();
                    Map<String, Object> conditions = new HashMap<>();
                    map.put(ParameterConfig.TABLE, ParameterConfig.JHCX_TRAIN_PASSENGER);
                    passenger.put(ParameterConfig.STATE, 2);
                    conditions.put(ParameterConfig.ORDERNO, orderNo);
                    conditions.put("idCard", idCard);
                    passenger.remove("carType");
                    map.put(ParameterConfig.COLUMNS, passenger);
                    map.put(ParameterConfig.CONDITIONS, conditions);
                    oPticketDAO.update(map);
                });
            }
            return JsonUtil.getChuanglvJson(100, "成功");
        }
    }

    private void changeOrderStatus(JSONObject paramJson, String orderNo, List<Map<String, Object>> passengerList) {
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setState(0);
        orderRecord.setOrderNo(orderNo);
        oPticketDAO.updateRecord(orderRecord);
        //乘客订单状态
        passengerList.forEach(passenger -> {
            Passenger passer = new Passenger();
            //恢复原来状态
            passer.setState("4");
            passer.setOrderNo(paramJson.getString(ParameterConfig.ORIGINALORDERNO));
            oPticketDAO.updatePassengerStatus(passer);
        });
        //改签单订单状态占座失败
        TrainOrder order = new TrainOrder();
        order.setOrderNo(orderNo);
        order.setState("0");
        oPticketDAO.updateOrder(order);
    }
}
